package com.mx.contror;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.mx.service.ExportExcelService;

/**
 * @author MX
 *
 */
@Controller
public class ExportExcelController {
	 @Resource(name = "ExportExcelService")
	    private ExportExcelService exportExcelService;
	 //导出表格的数据Excel
	  @RequestMapping("/exportExcel")
	  @ResponseBody
	  public Map<String,String> exportExcel(HttpServletResponse response, HttpServletRequest request) throws UnsupportedEncodingException{
		  System.out.println("-----------exportExcel----------");
		  String state="-1";
		  try {
			this.exportExcelService.exportExcel(request,response);
			state="1";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		  Map<String,String> map=new  HashMap<String,String>();
		  map.put("state", state);
	     return map;   
	  }
	  @RequestMapping("/downloadModelExcel")
	  public void downloadModelExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
		  File   downloadFile=new File("D:\\serverlData\\model\\用户信息模版.xlsx");//我们服务器模版路径
		  String modelname=downloadFile.getName();
		  exportExcelService.downloadModelExcel(request, response, downloadFile, modelname);
	  }
	  
	/**
	 * 用户导入文件(文件上传)
	 * @throws IOException 
	 * @throws IllegalStateException 
	 * @throws InvalidFormatException 
	 */
	  @RequestMapping("/uploadUserInfoExcel")
	  @ResponseBody
	public  String uploadUserInfoExcel(@RequestParam("importFile") MultipartFile multipartFile,HttpServletRequest request) throws IllegalStateException, IOException, InvalidFormatException{
		  String uploadUrl = "D://serverlData//usermodel//upload";
	      String filename=multipartFile.getOriginalFilename();
	      //存放文件目录
	      File dir = new File(uploadUrl);
			if (!dir.exists()) {
				dir.mkdirs();
			}
		File targetFile = new File(uploadUrl +"//"+ filename);
		if (!targetFile.exists()) {
			try {
				targetFile.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		multipartFile.transferTo(targetFile);   //文件上传 将我们的文件 copy到目标位置
		exportExcelService.readExcelToDateBase(targetFile);
	     return "ok";
	}
}
